#include <stdio.h>
#include <string.h>
#include<stdlib.h>

//打开文件
FILE *file_open(const char *path,const char *mode);

// 关闭文件 要创二级指针才能修改
int file_close(FILE **fp);

//结构体声明
typedef struct stu
{
    char name[100];
    int id;
    int grade;
} stu;

//结构体数组
stu class[18] =
    {
        {"刘备", 1, 90},
        {"关羽", 2, 80},
        {"张飞", 3, 70},
        {"诸葛亮", 4, 100},
        {"曹操", 5, 66},
        {"孙权", 6, 68},
        {"刘备", 7, 90},
        {"关羽", 8, 80},
        {"张飞", 9, 70},
        {"曹操", 10, 66},
};

int main(int argc, char const *argv[])
{
    stu class_1[10];
    // 打开文件
    FILE *fp = file_open("hello.txt", "r+");

    // 写入到文件
    for (int i = 0; i < 10; i++)
    {
        fprintf(fp, "|%d\t|%s\t|%d\n", class[i].id, class[i].name, class[i].grade);
    }

    //从文件中读取
    fp = file_open("hello.txt", "r+");
    for (int i = 0; i < 10; i++)
    {
        fscanf(fp, "|%d\t|%s\t|%d\n", &class_1[i].id, class_1[i].name, &class_1[i].grade);
    }

    //打印到终端
    for (int i = 0; i < 10; i++)
    {
        fprintf(stdout, "|%d\t|%s\t|%d\n", class_1[i].id, class_1[i].name, class_1[i].grade);
    }

    //关闭文件
    file_close(&fp);
    return 0;
}



// 打开文件
FILE *file_open(const char *path, const char *mode)
{
    FILE *fp = fopen(path,mode);
    if (fp==NULL)
    {
        printf("文件打开失败!\n");
        exit(-1);
    }
    return fp;
}

// 关闭文件 要创二级指针才能修改
int file_close(FILE **fp)
{
    fclose(*fp);
    *fp = NULL;
}